<template>
  <div>
    <div class="content row-flex-start" style="min-width:1500px;ovorflow-x:auto">
      <div class="left_map" id="left_map" @click="showChinaMap"></div>
      <div class="right_opetate row-center" id="right_opetate" @click="alter('1')">
      </div>
    </div>
    <!--弹框部分-->
    <van-popup v-model="show" bind:close="onClose" style="width: 60%;height: auto;margin: 10vh 10vw 10vh 10vw">
      <van-field
        readonly
        name="开始时间"
        :value="parseTime(value, '{y}-{m}-{d}')"
        label="开始时间"
        placeholder="点击选择时间"
        @click="showPicker = true"
      />
      <van-field
        readonly
        name="结束时间"
        :value="parseTime(value2, '{y}-{m}-{d}')"
        label="结束时间"
        placeholder="点击选择时间"
        @click="showPicker2 = true"
      />

      <div style="margin: 16px;">
        <van-button round block type="info" @click="subDitu()">提交</van-button>
      </div>
    </van-popup>


    <van-popup v-model="showPicker" position="bottom">
      <van-datetime-picker
        type="date"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
    <van-popup v-model="showPicker2" position="bottom">
      <van-datetime-picker
        type="date"
        @confirm="onConfirm2"
        @cancel="showPicker2 = false"
      />
    </van-popup>
  </div>

</template>

<script>
  import echarts from 'echarts'
  import china from 'echarts/map/json/china.json'
  import chianJson from '../../../static/map/china.json'
  import {signTaleDitu, listCityName} from "../api/tale";


  import axios from 'axios'

  echarts.registerMap('china', china)
  var provinces = ['shanghai', 'hebei', 'shanxi', 'neimenggu', 'liaoning', 'jilin', 'heilongjiang', 'jiangsu', 'zhejiang', 'anhui', 'fujian', 'jiangxi', 'shandong', 'henan', 'hubei', 'hunan', 'guangdong', 'guangxi', 'hainan', 'sichuan', 'guizhou', 'yunnan', 'xizang', 'shanxi1', 'gansu', 'qinghai', 'ningxia', 'xinjiang', 'beijing', 'tianjin', 'chongqing', 'xianggang', 'aomen', 'taiwan']
  var provincesText = ['上海', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '广西', '海南', '四川', '贵州', '云南', '西藏', '陕西', '甘肃', '青海', '宁夏', '新疆', '北京', '天津', '重庆', '香港', '澳门', '台湾']
  export default {
    name: "ditu2",
    created() {
    },
    mounted() {
      this.$nextTick(() => {
        //获取当前用户点亮的省、城市
        this.getCityNames();

      })
    },
    data() {
      return {
        map: {},
        token: this.getCookie("token"),
        showPicker: false,
        showPicker2: false,
        minDate: new Date(2015, 0, 1),
        maxDate: new Date(2025, 10, 1),
        currentDate: new Date(2021, 0, 17),
        show: false,
        value: '',
        value2: '',
        //当前子城市名
        cityName: '',
        //当前子城市code
        cityCode: '',
        //点亮的省、城市对象
        cityNames: [
        ]
      }
    },
    props: {},
    methods: {
      getCityNames() {
        listCityName({"accessToken": this.token})
          .then(res => {
            let datas = res.data.data;
            datas.map(item => {
              this.cityNames.push({
                name:item,
                itemStyle: {normal: {areaColor: '#FD9A9A'}}
              })
            })
            //渲染地图
            this.initMap();
            if(this.cityCode !=''){
              this.getProvinceMapOpt(this.cityCode);
            }
          })
      },
      subDitu() {
        let myTale = {
          frontDate: this.value,
          endDate: this.value2,
          cityName: this.cityName
        };
        signTaleDitu(myTale, {"accessToken": this.token})
          .then(res => {
            this.$toast.success("保存成功");
            this.show = false;
            this.getCityNames();
          })
      },
      onConfirm(time) {
        this.value = time;
        this.showPicker = false;
      },
      onConfirm2(time) {
        this.value2 = time;
        this.showPicker2 = false;
      },
      onClose() {
        this.setData({show: false});
      },
      convertData(data) {
        var res = [];
        for (var i = 0; i < data.length; i++) {
          var geoCoord = this.geoCoordMap[data[i].name];
          if (geoCoord) {
            res.push(geoCoord.concat(data[i].value).concat(data[i].name));
          }
        }
        return res;
      },
      getMapOpt(place) {
        const option = {
          backgroundColor: '#F3F3F3',
          //地图背景颜色
          //以下是地图标题，我在此处设空，需要的可以自己加上
          title: {
            text: '地图',
            left: 20,
            top: 20,
          },
          //以下是地图右侧“还原”“下载”工具框
          toolbox: {
            show: true,
            orient: 'vertical',
            left: 'right',
            top: 'center',
            feature: {
              restore: {},
              saveAsImage: {}
            }
          },
          geo: {
            map: place || 'china',
            regions: this.cityNames,
            label: {
              emphasis: {
                show: false
              },
              // 不需要显示地名可直接删除normal此项
              normal: {
                show: true, // 是否显示对应地名
                textStyle: {
                  color: 'rgba(0,0,0)'
                }
              }
            },
            roam: true,
            itemStyle: {
              normal: {
                areaColor: '#6FA7CE', //地图颜色
                borderColor: '#fff' //地图边线颜色
              },
              emphasis: {
                areaColor: '#B7DFED' //鼠标移入颜色
              }
            }
          },
          // 散点图
          series: [
            //   {
            //     name: '帝都',
            //     type: 'scatter',
            //     coordinateSystem: 'geo',
            //     data: this.convertData([
            //       {name: "北京", value: 9}
            //     ]),
            //     encode: {
            //       value: 2
            //     },
            //     symbolSize: 12,
            //     label: {
            //       normal: {
            //         show: false,//显示市区标签
            //         textStyle:{color:"#c71585"}//省份标签字体颜色
            //       },
            //       emphasis: {//对应的鼠标悬浮效果
            //         show: true,    //关闭文字 （这东西有问题得关）
            //         textStyle:{color:"#800080"}
            //       }
            //     },
            //     itemStyle: {
            //       normal: {
            //         borderWidth: .5,//区域边框宽度
            //         borderColor: '#009fe8',//区域边框颜色
            //         areaColor:"#ffefd5",//区域颜色
            //       },
            //       emphasis: {
            //         show:true,
            //         borderWidth: .5,
            //         borderColor: '#4b0082',
            //         areaColor:"#f47920",
            //       }
            //     }
            //   },
            // {
            //   type: 'effectScatter',  //特效散点图
            //   // rippleEffect: { // 涟漪效果
            //   //   scale: 5,
            //   //   brushType: 'stroke'
            //   // },
            //   coordinateSystem: 'geo', // 使用坐标
            //   name: "二线城市",
            //   data: [
            //     {name: "厦门", value: [118.11022,24.490474]},
            //     {name: "杭州", value: [120.19, 30.26]},
            //     {name: "成都", value: [104.06, 30.67]},
            //     {name: "武汉", value: [114.31, 30.52]},
            //   ]
            // },
            // {
            //   type: 'effectScatter',  //特效散点图
            //   rippleEffect: { // 涟漪效果
            //     scale: 5,
            //     brushType: 'stroke'
            //   },
            //   coordinateSystem: 'geo', // 使用坐标
            //   name: "三线城市",
            //   data: [
            //     {name: "拉萨", value: [91.11, 29.97]},
            //     {name: "乌鲁木齐", value: [87.68, 43.77]},
            //     {name: "西宁", value: [101.74, 36.56]},
            //     {name: "兰州", value: [103.73, 36.03]},
            //   ]
            // },
          ],
          legend: { // 图例组件
            left: '5%',
            bottom: '5%',
            orient: 'vertical', // 竖着排列
            data: ['一线城市', '二线城市', '三线城市']
          },
        }
        console.log(option)
        return option
      },
      // 显示中国地图
      showChinaMap() {
        const option = this.getMapOpt()
        this.map.setOption(option, true)
      },
      // 显示各省地图，这里使用axios请求本地文件，provice文件夹存在的位置为public/province（旧版本是static）
      getProvinceMapOpt(provinceAlphabet) {
        axios.get('./static/province/' + provinceAlphabet + '.json').then((s) => {
          echarts.registerMap(provinceAlphabet, s.data)
          const option = this.getMapOpt(provinceAlphabet)
          this.map.setOption(option, true)
        })
      },
      initMap() {
        var dom = document.getElementById('left_map')
        this.map = echarts.init(dom)
        const option = this.getMapOpt()
        if (option && typeof option === 'object') {
          this.map.setOption(option, true)
        }
        this.map.on('click', (param) => {
          // console.log(param)
          event.stopPropagation()// 阻止冒泡
          // 找到省份名
          const provinceIndex = provincesText.findIndex(x => {
            return param.name === x
          })
          //在这里判断provincesText中是否包含点击的省份名，有则渲染省级地图，无则无处理（需要可从此获得）
          if (provinceIndex === -1) {
            this.cityName = param.name;
            this.show = true;
            return;
          }
          const provinceAlphabet = provinces[provinceIndex];
          this.cityCode=provinceAlphabet;
          // 重新渲染各省份地图
          this.getProvinceMapOpt(provinceAlphabet)
        })
      }
    },
    computed: {}
  }
</script>

<style>
  .left_map {
    width: 1200px;
    height: 1000px;
  }

  .right_opetate {
    flex: 1;
    height: 100%;
    background: #404a59
  }
</style>
